<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务编码" prop="taskId">
        <el-input
          v-model="queryParams.taskId"
          placeholder="请输入任务编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售订单编码" prop="sordId">
        <el-input
          v-model="queryParams.sordId"
          placeholder="请输入销售订单编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="销售订单名" prop="sordName">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.sordName"-->
      <!--          placeholder="请输入销售订单名"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="计划编码" prop="planId">
        <el-input
          v-model="queryParams.planId"
          placeholder="请输入计划编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态(0未完成/1已完成)" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态(0未完成/1已完成)" clearable>
          <el-option
            v-for="dict in dict.type.task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务开始时间" prop="taskTime">
        <el-date-picker clearable
                        v-model="queryParams.taskTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择任务开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="任务结束时间" prop="taskFinTime">
        <el-date-picker clearable
                        v-model="queryParams.taskFinTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择任务结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:task:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:task:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:task:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车间任务id" align="center" prop="id" />
      <el-table-column label="任务编码" align="center" prop="taskId" />
      <el-table-column label="销售订单编码" align="center" prop="sordId" />
      <!--      <el-table-column label="销售订单名" align="center" prop="sordName" />-->
      <el-table-column label="计划编码" align="center" prop="planId" />
      <el-table-column label="任务状态(0未完成/1已完成)" align="center" prop="taskStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_status" :value="scope.row.taskStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="任务开始时间" align="center" prop="taskTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.taskTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务结束时间" align="center" prop="taskFinTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.taskFinTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:task:edit']"
          >领料</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCardOpen(scope.row)"
            v-hasPermi="['system:task:edit']"
          >拆卡</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:task:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:task:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车间任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务编码" prop="taskId">
          <el-input v-model="form.taskId" placeholder="请输入任务编码" />
        </el-form-item>

        <!--        <el-form-item label="销售订单编码" prop="sordId">-->
        <!--          <el-input v-model="form.sordId" placeholder="请输入销售订单编码" />-->
        <!--        </el-form-item>-->
        <el-form-item label="销售订单编码" prop="sordId" >
          <el-select v-model="form.sordId" filterable placeholder="请选择">
            <el-option v-for="item in sordinfoselectoption" :key="item.id" :label="item.sordId" :value="item.sordId">
            </el-option>
          </el-select>
        </el-form-item>


        <!--        <el-form-item label="销售订单名" prop="sordName">-->
        <!--          <el-input v-model="form.sordName" placeholder="请输入销售订单名" />-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="计划编码" prop="planId">-->
        <!--          <el-input v-model="form.planId" placeholder="请输入计划编码" />-->
        <!--        </el-form-item>-->
        <el-form-item label="计划编码" prop="planId" >
          <el-select v-model="form.planId" filterable placeholder="请选择">
            <el-option v-for="item in planinfoselectoption" :key="item.id" :label="item.planId" :value="item.planId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="任务状态(0未完成/1已完成)" prop="taskStatus">
          <el-select v-model="form.taskStatus" placeholder="请选择任务状态(0未完成/1已完成)">
            <el-option
              v-for="dict in dict.type.task_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务开始时间" prop="taskTime">
          <el-date-picker clearable
                          v-model="form.taskTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择任务开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务结束时间" prop="taskFinTime">
          <el-date-picker clearable
                          v-model="form.taskFinTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择任务结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--    拆卡对话框-->
    <el-dialog :title="title" :visible.sync="cardOpen" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务编码" prop="taskId">
          <el-input v-model="form.taskId" placeholder="请输入任务编码" style="width: 220px"/>
        </el-form-item>

        <el-form-item label="开始时间" prop="taskTime">
          <el-date-picker clearable
                          v-model="form.taskTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择任务开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="taskFinTime">
          <el-date-picker clearable
                          v-model="form.taskFinTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择任务结束时间">
          </el-date-picker>
        </el-form-item>
        <el-divider>产 品 列 表</el-divider>
        <el-table v-loading="loading" :data="needProcessList" border>
          <el-table-column label="产品" align="center" prop="prodId" />
          <el-table-column label="需加工数量" align="center" prop="procNum" v-model="form.procNum"/>

        </el-table>
        <el-divider>车 间 任 务 卡</el-divider>
        <el-button v-if="isVisible" style="margin-bottom: 10px;" type="primary" @click="processadd">添 加</el-button>
        <el-card shadow="always" style="border-radius: 15px;">
          <el-table style="border-radius: 15px;" v-loading="loading" border :data="form.mtrs">
            <el-table-column label="产品" align="" prop="mtrName" align="center">
              <template slot-scope="scope" >
                <el-select v-model="scope.row.prodId" filterable placeholder="请选择"
                           @change="(option) => mtrchang(option, scope.$index,scope)" :disabled="!isVisible">

                  <el-option v-for="item in needProcessList" :key="item.prodId" :label="item.prodId" :value="item.prodId">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="加工数量" align="center"  width="230px" >
              <template slot-scope="scope">
                <el-input-number id="inputNumber" v-model:value="scope.row.procNum" :min="0" :precision="0" :disabled="!isVisible"/>
              </template>
            </el-table-column>

            <el-table-column label="开始时间" align="center"  width="230px">
              <template slot-scope="scope">
                <!--                <el-input-number id="inputNumber" v-model:value="scope.row.prodNum" :min="0" :precision="0" :disabled="!isVisible"/>-->
                <el-date-picker clearable
                                v-model:value="scope.row.taskTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择任务开始时间"
                                style="width: 200px">
                </el-date-picker>
              </template>
            </el-table-column>

            <el-table-column label="结束时间" align="center"  width="230px">
              <template slot-scope="scope">
                <!--                <el-input-number id="inputNumber" v-model:value="scope.row.prodNum" :min="0" :precision="0" :disabled="!isVisible"/>-->
                <el-date-picker clearable
                                v-model:value="scope.row.taskFinTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择任务结束时间"
                                style="width: 200px">
                </el-date-picker>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isVisible">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="processadd(scope.$index, scope.row)"
                           v-hasPermi="['mes:proinfo:edit']">增加</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="processdel(scope.$index)"
                           v-hasPermi="['mes:proinfo:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCardForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {listTask, getTask, delTask, addTask, updateTask, cardOpening} from "@/api/system/task";
import {listSord} from "@/api/system/sord";
import {listPlan} from "@/api/system/plan";
import {listProd} from "@/api/system/prod";
import {addCard} from "@/api/system/card";

export default {
  name: "Task",
  dicts: ['task_status'],
  data() {
    return {
      isVisible : false,

      //销售订单下拉框数据
      sordinfoselectoption:[],
      //计划下拉框数据
      planinfoselectoption:[],
      //需加工产品列表
      needProcessList:[],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车间任务表格数据
      taskList: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //拆卡弹出层
      cardOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskId: null,
        sordId: null,
        sordName: null,
        planId: null,
        taskStatus: null,
        taskTime: null,
        taskFinTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskId: [
          { required: true, message: "任务编码不能为空", trigger: "blur" }
        ],
        sordId: [
          { required: true, message: "销售订单编码不能为空", trigger: "blur" }
        ],
        sordName: [
          { required: true, message: "销售订单名不能为空", trigger: "blur" }
        ],
        planId: [
          { required: true, message: "计划编码不能为空", trigger: "blur" }
        ],
        taskStatus: [
          { required: true, message: "任务状态(0未完成/1已完成)不能为空", trigger: "change" }
        ],
        taskTime: [
          { required: true, message: "任务开始时间不能为空", trigger: "blur" }
        ],
        taskFinTime: [
          { required: true, message: "任务结束时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    mtrchang(option, index,scope) {
      let ss = this.needProcessList.find(item => item.prodId == option)
      if(ss) {
        this.form.mtrs[index].id = ss.id
        // // this.form.mtrs[index].sordId = this.form.sordId//销售订单编码
        // this.form.mtrs[index].prodId = ss.prodId// 产品编码
        // this.form.mtrs[index].prodNum = this.form.prodNum //产品数量

        this.form.mtrs[index].taskId = this.form.taskId;//任务编码
        this.form.mtrs[index].prodId = ss.prodId;//产品编码
        this.form.mtrs[index].procNum = this.form.procNum;//this.form.mtrs[index].procNum = scope.row.procNum;// this.form.mtrs[index].procNum = this.form.prodNum;//产品数量
        this.form.mtrs[index].taskTime = this.form.taskTime;//开始时间
        this.form.mtrs[index].taskFinTime = this.form.taskFinTime;//结束时间

      }


      // this.form.mtrs[index].id = option.id
      // this.form.mtrs[index].taskCardId = this.form.taskCardId;//任务卡编码

      // this.form.mtrs[index].taskId = this.form.taskId;//任务编码
      // this.form.mtrs[index].prodId = option.prodId;//产品编码
      // this.form.mtrs[index].prodNum = option.prodNum;//产品数量
      // this.form.mtrs[index].taskTime = option.taskTime;//开始时间
      // this.form.mtrs[index].taskFinTime = option.taskFinTime;//结束时间

      // this.form.mtrs[index].taskId = this.form.taskId;//任务编码
      // this.form.mtrs[index].prodId = this.form.prodId;//产品编码
      // this.form.mtrs[index].prodNum = this.form.prodNum;//产品数量
      // this.form.mtrs[index].taskTime = this.form.taskTime;//开始时间
      // this.form.mtrs[index].taskFinTime = this.form.taskFinTime;//结束时间

    },

    processdel(index) {
      this.form.mtrs.splice(index, 1)
    },

    processadd(index, row) {
      if (index != undefined) {

        this.form.mtrs.splice(index + 1, 0,
          {
            id:null,
            // sordId:null,
            prodId:null,//产品编码
            procNum: 0,//产品数量
            taskTime : '',//开始时间
            taskFinTime : ''//结束时间

          }
        )
      } else {
        this.form.mtrs.push(
          {
            id:null,
            // sordId:null,
            prodId:null,
            procNum: 0,
            taskTime : '',//开始时间
            taskFinTime : ''//结束时间

          }
        )
      }
    },

    /** 查询车间任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      //销售列表
      listSord().then((res) => {
        this.sordinfoselectoption = res.rows
      });
      //计划列表
      listPlan().then((res) => {
        this.planinfoselectoption = res.rows
      });
      //需加工产品列表
      listProd().then((res) => {
        this.needProcessList = res.rows
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.cardOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskId: null,
        sordId: null,
        sordName: null,
        planId: null,
        taskStatus: null,
        taskTime: null,
        taskFinTime: null,
        procNum:0,
        mtrs:[],
        submtrs:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车间任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改车间任务";
      });
    },
    /** 拆卡按钮操作*/
    handleCardOpen(row) {
      this.reset();
      this.isVisible = true;
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        this.needProcessList = this.needProcessList.filter(item => item.sordId === this.form.sordId);
        // 遍历列表中的每个对象，将prodNum字段更名为procNum
        this.needProcessList.forEach(item => {
          item.procNum = item.prodNum;
          delete item.prodNum;
        });
        // this.form.mtrs = this.needProcessList;
        // this.form.mtrs = [];
        this.form.mtrs = JSON.parse(JSON.stringify(this.needProcessList));
        this.form.mtrs.forEach(mtr => {
          mtr.taskTime = this.form.taskTime;
          mtr.taskFinTime = this.form.taskFinTime;
        });
        this.cardOpen = true;
        this.title = "车间任务拆卡";
      });
    },
    /** 拆卡提交 */
    submitCardForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // cardOpening(this.form).then(response => {
          //   this.$modal.msgSuccess("拆卡成功");
          //   this.cardOpen = false;
          //   this.getList();
          // });

          addCard(this.form).then(response => {
            this.$modal.msgSuccess("拆卡成功");
            this.cardOpen = false;
            this.getList();
          });

        }
      });
    },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除车间任务编号为"' + ids + '"的数据项？').then(function() {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    }
  },
  watch: {
    // 监听计划编码的变化
    'form.planId'(newPlanId) {
      // 找到与新计划编码对应的销售订单编码
      const matchingSord = this.planinfoselectoption.find(item => item.planId === newPlanId);
      if (matchingSord) {
        this.form.sordId = matchingSord.sordId;
      } else {
        // 如果找不到匹配的，可以重置或做其他处理
        this.form.sordId = ""; // 或者其他默认值
      }
    },

    // 监听销售订单编码的变化
    'form.sordId'(newSordId) {
      // 找到与新销售订单编码对应的计划编码
      const matchingPlan = this.planinfoselectoption.find(item => item.sordId === newSordId);
      if (matchingPlan) {
        this.form.planId = matchingPlan.planId;
      } else {
        // 如果找不到匹配的，可以重置或做其他处理
        this.form.planId = ""; // 或者其他默认值
      }
    }
  }
};
</script>

